<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .time {
        width: 200px;
        height: 200px;
        margin: 100px auto;
      }
      h4 {
        padding-left: 50px;
      }
      div span {
        display: inline-block;
        height: 50px;
        width: 50px;
        color: #fff;
        font-size: 18px;
        background-color: red;
        text-align: center;
        line-height: 50px;
      }
    </style>
  </head>
  <body>
    <div class="time">
      <h4>秒杀倒计时</h4>
      <span class="hour"></span>
      <span class="minute"></span>
      <span class="second"></span>
    </div>
    <script>
      //1.获取三个元素
      let hour = document.querySelector('.hour')
      let minute = document.querySelector('.minute')
      let second = document.querySelector('.second')

      let inputTime = new Date('2024-11-21 11:00:00') //返回用户输入时间总的毫秒数，用户输入倒计时的结束时间
      countDown() //先调用一次函数 防止有空白 采取函数封装

      //开启定时器
      setInterval(countDown, 1000)
      // 倒计时函数
      function countDown() {
        let nowTime = new Date() //返回当前时间总的毫秒数
        let times = (inputTime - nowTime) / 1000 //times是剩余时间总的秒数

        // let d = parseInt(times / 60 / 60 / 24);
        // d = d < 10 ? '0' + d : d;
        //不需要天
        let h = parseInt((times / 60 / 60) % 24) //时
        h = h < 10 ? '0' + h : h
        let m = parseInt((times / 60) % 60) //分
        m = m < 10 ? '0' + m : m
        let s = parseInt(times % 60)
        s = s < 10 ? '0' + s : s
        // return d + '天' + h + '时' + 'm' + '分' + 's' + '秒';
        //不需要返回值
        //修改盒子内时间 让他们等于对应数值
        hour.innerHTML = h
        minute.innerHTML = m
        second.innerHTML = s
      }
    </script>
  </body>
</html>
